﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using COSL_Ticket_SP_DAL;
using Microsoft.SharePoint;

namespace COSL_Ticket.LeftNavigation
{
    public partial class LeftNavigationUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    NavigationInitial();
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ErrorMessage.Text = ex.ToString();
#endif
            }
        }

        private void NavigationInitial()
        {
            Guid siteId = SPContext.Current.Site.ID;
            Guid webId = SPContext.Current.Web.ID;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(siteId))
                {
                    using (SPWeb web = site.OpenWeb(webId))
                    {
                        SPList navigationList = web.Lists.TryGetList(ConstName.NavigationListName);
                        //Check whether navigation list exists
                        if (navigationList != null)
                        {
                            //If exist
                            //Get role of current user
                            string curUserRole = "";
                            SPUser curUser = web.EnsureUser(Page.User.Identity.Name);
                            Operator curOperator = new Operator(Page.User.Identity.Name);
                            TicketAdmin curTicketAdmin = new TicketAdmin(Page.User.Identity.Name);

                            if (curOperator.OperatorExist)
                            {
                                curUserRole = "经办人";
                            }
                            if (curTicketAdmin.TicketAdminExist)
                            {
                                curUserRole = "票务中心";
                            }
                            SPField scopeField = navigationList.Fields["访问范围"];
                            SPField sortField = navigationList.Fields["序号"];
                            SPQuery query = new SPQuery();
                            query.Query = "<Where><Eq><FieldRef Name='" + scopeField.InternalName + "'/>" +
                            "<Value Type='Text'>" + curUserRole + "</Value></Eq></Where>" +
                            "<OrderBy><FieldRef Name='" + sortField.InternalName + "' Ascending='TRUE'></FieldRef></OrderBy>";
                            SPListItemCollection resultItems = navigationList.GetItems(query);
                            StringBuilder navText = new StringBuilder();
                            navText.Append("<h3> " + curUser.Name + "</h3><ul>");
                            string liTemplateStr = "<li><a href='{1}' target='{2}'><span>{0}</span></a>";
                            foreach (SPListItem resultItem in resultItems)
                            {
                                string parentName = Convert.ToString(resultItem["父节点"]);
                                string nodeUrl = Convert.ToString(resultItem["链接"]);
                                if (!string.IsNullOrEmpty(nodeUrl))
                                {
                                    SPFieldUrlValue value = new SPFieldUrlValue(resultItem["链接"].ToString());
                                    nodeUrl = value.Url;
                                }

                                //Query level1 nodes
                                if (string.IsNullOrEmpty(parentName))
                                {
                                    if (string.IsNullOrEmpty(nodeUrl))
                                    {
                                        navText.AppendFormat(liTemplateStr, resultItem.Title, "#", "_self");
                                    }
                                    else
                                    {
                                        navText.AppendFormat(liTemplateStr, resultItem.Title, nodeUrl, "_self");
                                    }
                                    //Query level2 nodes
                                    SPQuery subQuery = new SPQuery();
                                    subQuery.Query = "<Where><Eq><FieldRef Name='" + navigationList.Fields["父节点"].InternalName + "'/>" +
                                    "<Value Type='Text'>" + resultItem.Title + "</Value></Eq></Where>" +
                                    "<OrderBy><FieldRef Name='" + sortField.InternalName + "' Ascending='TRUE'></FieldRef></OrderBy>";
                                    SPListItemCollection subResultItems = navigationList.GetItems(subQuery);
                                    foreach (SPListItem subResultItem in subResultItems)
                                    {
                                        string subNodeUrl = Convert.ToString(subResultItem["链接"]);
                                        if (!string.IsNullOrEmpty(subNodeUrl))
                                        {
                                            SPFieldUrlValue value = new SPFieldUrlValue(subResultItem["链接"].ToString());
                                            nodeUrl = value.Url;
                                        }
                                        string liTemplateStr1 = "<li><a href='{1}' target='{2}'>&nbsp;&nbsp;<span>{0}</span></a>";
                                        navText.AppendFormat(liTemplateStr1, "   " + subResultItem.Title, nodeUrl, "_self");
                                        navText.Append("</li>");
                                    }
                                }

                                //获取常用链接 新窗口打开
                                if (resultItem.Title == "常用链接")
                                {
                                }
                                ltLeftNavigation.Text = navText.ToString();
                            }
                            navText.Append("</ul>");
                        }
                        else
                        {
                            //If not exist
                            ErrorMessage.Text = ConstName.NavigationListCannotfound;
                        }
                    }
                }
            });
        }
    }
}
